#include <iostream>
#include <filesystem>
#include "rapidjson//document.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/prettywriter.h"

#include <filesystem>
#include <fstream>
#include <future>
#include <thread>
#include <windows.h>

using namespace std;
using namespace rapidjson;

void childprocess(string exe_path, string param)
{
    const string command = filesystem::absolute(exe_path).generic_string() + " " + param;

    // 执行另一个程序，并将输出重定向到FILE指针
    FILE *pipe = _popen(command.c_str(), "w");
    if (pipe == nullptr)
    {
        cout << "无法执行该程序" << endl;
        return;
    }

    // 从其他程序读取输出
    char buffer[128];
    while (fgets(buffer, sizeof(buffer), pipe) != nullptr)
    {
        cout << buffer;
    }

    // 关闭FILE指针和其他程序
    _pclose(pipe);
}

int runExternalProgram()
{
    std::string programPath = "E:/Project/Repositories/cpp/cpp/httpserver/dist/py/dist/ws/ws.exe";
    std::string commandLineArgs = "\"{\\\"allowed_origins\\\": [\\\"http://127.0.0.1:6660\\\"]}\"";

    STARTUPINFO startupInfo;
    PROCESS_INFORMATION processInfo;
    ZeroMemory(&startupInfo, sizeof(startupInfo));
    ZeroMemory(&processInfo, sizeof(processInfo));
    startupInfo.cb = sizeof(startupInfo);

    // 启动另一个程序
    if (!CreateProcess(NULL, (LPSTR)(programPath + " " + commandLineArgs).c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo))
    {
        std::cout << "Failed to create process: " << GetLastError() << std::endl;
        return 1;
    }

    // 打印子进程的进程ID
    std::cout << "Child process ID: " << processInfo.dwProcessId << std::endl;

    // 监听消息
    while (true)
    {
        // 检查子进程是否已经退出
        DWORD exitCode;
        if (GetExitCodeProcess(processInfo.hProcess, &exitCode) && exitCode != STILL_ACTIVE)
        {
            break;
        }

        // 读取子进程输出
        char buffer[1024];
        DWORD bytesRead;
        if (ReadFile(processInfo.hProcess, buffer, sizeof(buffer) - 1, &bytesRead, NULL) && bytesRead > 0)
        {
            buffer[bytesRead] = '0';
            std::cout << buffer << std::endl;
        }

        Sleep(100); // 可以适当调整等待时间
    }

    cout << 1323 << endl;

    // 关闭句柄
    CloseHandle(processInfo.hProcess);
    CloseHandle(processInfo.hThread);

    // 返回一个结果或消息
    return 42;
}

int main()
{
    // 启动异步进程
    std::future<int> future = std::async(std::launch::async, runExternalProgram);

    // 在主进程中执行其他任务

    // 等待子线程的完成
    future.wait();

    // 获取异步进程的返回值或消息
    int result = future.get();

    // 处理返回值或消息
    std::cout << "Received result: " << result << std::endl;

    cout << 133122 << endl;
    // system("pause");

    return 0;
}